import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_demotest/view_models/login.view.model.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:provider/provider.dart';

class LoginToPage extends StatelessWidget {
  const LoginToPage({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => LoginViewModel(),
      child: Scaffold(
        appBar: AppBar(),
        body: const LoginForm(),
      ),
    );
  }
}

class LoginForm extends StatefulWidget {
  const LoginForm({super.key});

  @override
  LoginFormState createState() => LoginFormState();
}

class LoginFormState extends State<LoginForm> {
  late TextEditingController phoneController;
  late TextEditingController captchaController;
  final FocusNode _focusNode = FocusNode();
  bool _isTimerRunning = false; // 添加计时器状态
  int _countdown = 60; // 倒计时秒数
  Timer? _timer; // 计时器实例

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 100), () {
      if (mounted) FocusScope.of(context).requestFocus(_focusNode);
    });
    final loginViewModel = Provider.of<LoginViewModel>(context, listen: false);
    phoneController =
        TextEditingController(text: loginViewModel.loginForm['phone']);
    captchaController =
        TextEditingController(text: loginViewModel.loginForm['captcha']);
  }

  @override
  void dispose() {
    _timer?.cancel(); // 清理计时器
    phoneController.dispose();
    captchaController.dispose();
    super.dispose();
  }

  // 添加开始倒计时的方法
  void _startTimer() {
    setState(() {
      _isTimerRunning = true;
      _countdown = 60;
    });

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 0) {
          _countdown--;
        } else {
          _isTimerRunning = false;
          timer.cancel();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final loginViewModel = Provider.of<LoginViewModel>(context);
    return Container(
      height: 400,
      padding: EdgeInsets.all(40),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Align(
            alignment: Alignment.topLeft,
            child: Text(
              '输入你的手机号',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
            ),
          ),
          SizedBox(
            height: 125,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextField(
                  keyboardType: TextInputType.number,
                  maxLength: 11,
                  buildCounter: (BuildContext context,
                          {int? currentLength,
                          int? maxLength,
                          bool? isFocused}) =>
                      null,
                  focusNode: _focusNode,
                  controller: phoneController,
                  decoration: InputDecoration(
                    hintText: "手机号",
                    filled: true,
                    fillColor: Colors.grey[200],
                    border: InputBorder.none,
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(50),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(50),
                    ),
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 20,
                    ),
                  ),
                  onChanged: (value) {
                    loginViewModel.setPhone(value);
                  },
                ),
                Stack(
                  children: [
                    TextField(
                      keyboardType: TextInputType.number,
                      maxLength: 11,
                      buildCounter: (BuildContext context,
                              {int? currentLength,
                              int? maxLength,
                              bool? isFocused}) =>
                          null,
                      controller: captchaController,
                      decoration: InputDecoration(
                        hintText: "验证码",
                        filled: true,
                        fillColor: Colors.grey[200],
                        border: InputBorder.none,
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(50),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(50),
                        ),
                        contentPadding: EdgeInsets.symmetric(horizontal: 20),
                      ),
                      onChanged: (value) {
                        loginViewModel.setCaptcha(value);
                      },
                    ),
                    Positioned(
                      right: 10,
                      child: TextButton(
                        onPressed: _isTimerRunning
                            ? null
                            : () {
                                String phone = phoneController.text;
                                String regexPhoneNumber =
                                    r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$';
                                RegExp phoneRegExp = RegExp(regexPhoneNumber);
                                if (!phone.isNotEmpty) {
                                  SmartDialog.showToast(
                                    '请输入手机号',
                                    alignment: Alignment.topCenter,
                                  );
                                  return;
                                } else if (!phoneRegExp.hasMatch(phone)) {
                                  SmartDialog.showToast(
                                    '手机号格式错误',
                                    alignment: Alignment.topCenter,
                                  );
                                  return;
                                }
                                loginViewModel.getCaptcha();
                                _startTimer();
                              },
                        child: Text(
                          _isTimerRunning ? "$_countdown s" : "获取验证码",
                          style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                            color: _isTimerRunning ? Colors.grey : null,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          ElevatedButton(
            onPressed: () => loginViewModel.login(context),
            style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0)),
            child: Ink(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [
                    Colors.deepPurple.shade500,
                    Colors.purpleAccent,
                    Colors.purpleAccent
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  stops: [0, 0.8, 0],
                ),
                borderRadius: BorderRadius.circular(30.0),
              ),
              child: Container(
                alignment: Alignment.center,
                height: 50,
                width: 300,
                child: Text(
                  '登录',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
